<template>
	<div class="satellite-track-container">
		<!-- 轨道设计器侧边面板 -->
		<div class="orbit-designer-panel" :class="{ 'panel-visible': orbitDesignerVisible }">
			<div class="panel-header">
				<h3>轨道设计器</h3>
				<el-button type="text" @click="orbitDesignerVisible = false" class="close-button">
					<el-icon><Close /></el-icon>
				</el-button>
			</div>
			<div class="panel-content">
				<OrbitDesigner :cesium-viewer="viewer" />
			</div>
		</div>

		<!-- 主视图容器 -->
		<div class="main-view" :class="{ 'with-panel': orbitDesignerVisible }">
			<div id="cesiumContainer"></div>
		</div>
	</div>

	<div class="operate_container">
		<div class="menu_button" @click="drawer = !drawer" title="卫星星座选择">
			<img src="../../assets/menu.svg" width="28" height="28" alt="卫星星座选择" />
		</div>
		<div class="selected_button" @click="selectedDrawer = !selectedDrawer" title="已选卫星列表">
			<img src="../../assets/import.svg" width="28" height="28" alt="已选卫星列表" />
		</div>
		<div class="menu_button" @click="cacheDrawer = !cacheDrawer" title="缓存管理">
			<img src="../../assets/refresh-svgrepo-com.svg" width="28" height="28" alt="缓存" />
		</div>
		<div
			class="earth_rotation_button"
			@click="toggleEarthRotation"
			:title="earthRotationEnabled ? '关闭地球自转' : '开启地球自转'"
			:class="{ active: earthRotationEnabled }"
		>
			<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
				<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" />
				<path d="M8 12c0-2.21 1.79-4 4-4s4 1.79 4 4-1.79 4-4 4" stroke="currentColor" stroke-width="2" fill="none" />
				<path d="M12 8v8" stroke="currentColor" stroke-width="1" fill="none" />
				<path d="M8 12h8" stroke="currentColor" stroke-width="1" fill="none" />
			</svg>
		</div>
		<div class="menu_button" @click="orbitDesignerVisible = !orbitDesignerVisible" title="轨道设计器">
			<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
				<ellipse
					cx="12"
					cy="12"
					rx="8"
					ry="4"
					stroke="currentColor"
					stroke-width="2"
					fill="none"
					transform="rotate(30 12 12)"
				/>
				<ellipse
					cx="12"
					cy="12"
					rx="6"
					ry="3"
					stroke="currentColor"
					stroke-width="1.5"
					fill="none"
					transform="rotate(-30 12 12)"
				/>
				<circle cx="12" cy="12" r="2" fill="currentColor" />
			</svg>
		</div>
	</div>

	<el-drawer v-model="drawer" title="卫星星座选择" direction="ltr" size="400px">
		<div class="satellite_selection_container">
			<!-- 卫星集合表格 -->
			<div class="satellite_category_table">
				<div class="table_header">卫星集合</div>
				<el-table :data="specialSatelliteData" class="satellite_table" :show-header="false">
					<el-table-column prop="label">
						<template #default="scope">
							<span class="satellite_name">{{ scope.row.label }}</span>
						</template>
					</el-table-column>
					<el-table-column width="100" align="center">
						<template #default="scope">
							<span class="satellite_count">{{ getConstellationCount(scope.row.value) }}</span>
						</template>
					</el-table-column>
					<el-table-column width="80" align="center">
						<template #default="scope">
							<el-checkbox
								v-model="checked"
								:label="scope.row.value"
								@change="handleSatelliteChange"
								:disabled="checked.length >= 5 && !checked.includes(scope.row.value)"
							/>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 气象和地球资源卫星表格 -->
			<div class="satellite_category_table">
				<div class="table_header">气象和地球资源卫星</div>
				<el-table :data="weatherSatelliteData" class="satellite_table" :show-header="false">
					<el-table-column prop="label">
						<template #default="scope">
							<span class="satellite_name">{{ scope.row.label }}</span>
						</template>
					</el-table-column>
					<el-table-column width="100" align="center">
						<template #default="scope">
							<span class="satellite_count">{{ getConstellationCount(scope.row.value) }}</span>
						</template>
					</el-table-column>
					<el-table-column width="80" align="center">
						<template #default="scope">
							<el-checkbox
								v-model="checked"
								:label="scope.row.value"
								@change="handleSatelliteChange"
								:disabled="checked.length >= 5 && !checked.includes(scope.row.value)"
							/>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 通讯卫星表格 -->
			<div class="satellite_category_table">
				<div class="table_header">通讯卫星</div>
				<el-table :data="communicationSatelliteData" class="satellite_table" :show-header="false">
					<el-table-column prop="label">
						<template #default="scope">
							<span class="satellite_name">{{ scope.row.label }}</span>
						</template>
					</el-table-column>
					<el-table-column width="100" align="center">
						<template #default="scope">
							<span class="satellite_count">{{ getConstellationCount(scope.row.value) }}</span>
						</template>
					</el-table-column>
					<el-table-column width="80" align="center">
						<template #default="scope">
							<el-checkbox
								v-model="checked"
								:label="scope.row.value"
								@change="handleSatelliteChange"
								:disabled="checked.length >= 5 && !checked.includes(scope.row.value)"
							/>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 导航卫星表格 -->
			<div class="satellite_category_table">
				<div class="table_header">导航卫星</div>
				<el-table :data="navigationSatelliteData" class="satellite_table" :show-header="false">
					<el-table-column prop="label">
						<template #default="scope">
							<span class="satellite_name">{{ scope.row.label }}</span>
						</template>
					</el-table-column>
					<el-table-column width="100" align="center">
						<template #default="scope">
							<span class="satellite_count">{{ getConstellationCount(scope.row.value) }}</span>
						</template>
					</el-table-column>
					<el-table-column width="80" align="center">
						<template #default="scope">
							<el-checkbox
								v-model="checked"
								:label="scope.row.value"
								@change="handleSatelliteChange"
								:disabled="checked.length >= 5 && !checked.includes(scope.row.value)"
							/>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 科学卫星表格 -->
			<div class="satellite_category_table">
				<div class="table_header">科学卫星</div>
				<el-table :data="scientificSatelliteData" class="satellite_table" :show-header="false">
					<el-table-column prop="label">
						<template #default="scope">
							<span class="satellite_name">{{ scope.row.label }}</span>
						</template>
					</el-table-column>
					<el-table-column width="100" align="center">
						<template #default="scope">
							<span class="satellite_count">{{ getConstellationCount(scope.row.value) }}</span>
						</template>
					</el-table-column>
					<el-table-column width="80" align="center">
						<template #default="scope">
							<el-checkbox
								v-model="checked"
								:label="scope.row.value"
								@change="handleSatelliteChange"
								:disabled="checked.length >= 5 && !checked.includes(scope.row.value)"
							/>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 其他卫星表格 -->
			<div class="satellite_category_table">
				<div class="table_header">其他卫星</div>
				<el-table :data="miscellaneousSatelliteData" class="satellite_table" :show-header="false">
					<el-table-column prop="label">
						<template #default="scope">
							<span class="satellite_name">{{ scope.row.label }}</span>
						</template>
					</el-table-column>
					<el-table-column width="100" align="center">
						<template #default="scope">
							<span class="satellite_count">{{ getConstellationCount(scope.row.value) }}</span>
						</template>
					</el-table-column>
					<el-table-column width="80" align="center">
						<template #default="scope">
							<el-checkbox
								v-model="checked"
								:label="scope.row.value"
								@change="handleSatelliteChange"
								:disabled="checked.length >= 5 && !checked.includes(scope.row.value)"
							/>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
	</el-drawer>

	<!-- 缓存管理抽屉 -->
	<el-drawer v-model="cacheDrawer" title="缓存管理中心" direction="ltr" size="400px">
		<div class="cache_management_container">
			<div class="cache_list">
				<!-- TLE数据缓存 -->
				<div class="cache_group">
					<div class="cache_group_header">
						<div class="cache_info">
							<span class="cache_name">🛰️ TLE数据缓存</span>
							<span class="cache_count_text">({{ cacheStats.tleGroups }}组)</span>
						</div>
						<div class="cache_controls">
							<el-button type="warning" @click="handleManualTleUpdate" :disabled="isUpdatingTle" size="small">
								<el-icon><Refresh /></el-icon>
								手动更新
							</el-button>
							<el-button
								type="danger"
								@click="handleClearCache"
								:disabled="cacheStats.tleGroups === 0 || isUpdatingTle"
								size="small"
							>
								<el-icon><Delete /></el-icon>
								清空缓存
							</el-button>
						</div>
					</div>

					<div class="cache_details">
						<!-- 更新进度 -->
						<div v-if="isUpdatingTle" class="update_progress">
							<el-progress
								:percentage="
									updateProgress.total > 0 ? Math.round((updateProgress.current / updateProgress.total) * 100) : 0
								"
								:status="updateProgress.current === updateProgress.total ? 'success' : undefined"
							/>
							<p class="progress_text">
								正在更新: {{ updateProgress.currentGroup }} ({{ updateProgress.current }}/{{ updateProgress.total }})
							</p>
						</div>

						<!-- TLE缓存统计信息 -->
						<div class="cache_stats">
							<div class="stat_item">
								<span class="stat_label">总大小:</span>
								<span class="stat_value">{{ formatFileSize(cacheStats.totalSize) }}</span>
							</div>
							<div class="stat_item">
								<span class="stat_label">最早缓存:</span>
								<span class="stat_value">{{ formatTime(cacheStats.oldestTimestamp) }}</span>
							</div>
							<div class="stat_item">
								<span class="stat_label">最新缓存:</span>
								<span class="stat_value">{{ formatTime(cacheStats.newestTimestamp) }}</span>
							</div>
						</div>
					</div>
				</div>

				<!-- 轨道缓存 -->
				<div class="cache_group">
					<div class="cache_group_header">
						<div class="cache_info">
							<span class="cache_name">🛰️ 轨道缓存</span>
							<span class="cache_count_text">({{ formatPredictionLength(orbitPredictionHours) }})</span>
						</div>
						<div class="cache_controls">
							<el-select
								v-model="orbitPredictionHours"
								@change="handlePredictionLengthChange"
								size="small"
								style="width: 100px"
							>
								<el-option label="12小时" :value="12" />
								<el-option label="24小时" :value="24" />
								<el-option label="48小时" :value="48" />
								<el-option label="72小时" :value="72" />
								<el-option label="7天" :value="168" />
								<el-option label="15天" :value="360" />
								<el-option label="30天" :value="720" />
							</el-select>
						</div>
					</div>

					<div class="cache_details">
						<div class="cache_stats">
							<div class="stat_item" v-if="orbitPredictionHours > 72">
								<el-alert title="性能提示" type="warning" :closable="false" show-icon size="small">
									长时间预测可能影响系统性能，建议根据需要选择合适的时长。
								</el-alert>
							</div>
						</div>
					</div>
				</div>

				<!-- 图层缓存 -->
				<div class="cache_group">
					<div class="cache_group_header">
						<div class="cache_info">
							<span class="cache_name">🗺️ 图层缓存</span>
							<span class="cache_count_text">({{ mapCacheStats.tileCount }}瓦片)</span>
						</div>
						<div class="cache_controls">
							<div class="visibility-switch">
								<span class="switch-label">{{ isMapCacheEnabled ? '已启用' : '已禁用' }}</span>
								<el-switch
									v-model="isMapCacheEnabled"
									@change="toggleMapCache"
									active-color="#95D475"
									inactive-color="#dcdfe6"
								/>
							</div>
							<el-button type="danger" @click="handleClearMapCache" :disabled="!isMapCacheEnabled" size="small">
								<el-icon><Delete /></el-icon>
								清空缓存
							</el-button>
						</div>
					</div>

					<div class="cache_details">
						<div class="cache_stats">
							<div class="stat_item">
								<span class="stat_label">总大小:</span>
								<span class="stat_value">{{ formatFileSize(mapCacheStats.totalSize) }}</span>
							</div>
							<div class="stat_item">
								<span class="stat_label">最早缓存:</span>
								<span class="stat_value">{{ formatTime(mapCacheStats.oldestTimestamp) }}</span>
							</div>
							<div class="stat_item">
								<span class="stat_label">最新缓存:</span>
								<span class="stat_value">{{ formatTime(mapCacheStats.newestTimestamp) }}</span>
							</div>
						</div>
					</div>
				</div>

				<!-- 地球自转控制 -->
				<div class="cache_group">
					<div class="cache_group_header">
						<div class="cache_info">
							<span class="cache_name">🌍 地球自转控制</span>
							<span class="cache_count_text">({{ earthRotationEnabled ? '已启用' : '已禁用' }})</span>
						</div>
						<div class="cache_controls">
							<div class="visibility-switch">
								<span class="switch-label">{{ earthRotationEnabled ? '开启' : '关闭' }}</span>
								<el-switch
									v-model="earthRotationEnabled"
									@change="toggleEarthRotation"
									active-color="#95D475"
									inactive-color="#dcdfe6"
								/>
							</div>
						</div>
					</div>

					<div class="cache_details">
						<div class="cache_stats">
							<div class="stat_item">
								<span class="stat_label">功能状态:</span>
								<span class="stat_value">{{ earthRotationEnabled ? '光照效果已启用' : '光照效果已禁用' }}</span>
							</div>
							<div class="stat_item">
								<span class="stat_label">适用模式:</span>
								<span class="stat_value">2D/3D模式通用</span>
							</div>
							<div class="stat_item">
								<span class="stat_label">效果说明:</span>
								<span class="stat_value">显示地球昼夜变化和阴影</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</el-drawer>

	<el-drawer v-model="selectedDrawer" title="已选卫星列表" direction="rtl" size="400px">
		<div class="selected_satellites_container">
			<div class="satellite_list" v-if="selectedSatellites.size > 0">
				<div class="satellite_group" v-for="[groupValue, groupInfo] in selectedSatellites" :key="groupValue">
					<!-- 卫星组标题 -->
					<div class="satellite_group_header">
						<div class="satellite_info">
							<span class="satellite_name">{{ groupInfo.label }}</span>
							<span class="satellite_count_text">({{ getSatelliteCount(groupValue) }}颗)</span>
						</div>
						<div class="satellite_controls">
							<div class="visibility-switch">
								<span class="switch-label">全部显示</span>
								<el-switch
									:model-value="groupAllVisibility.get(groupValue) || false"
									@update:model-value="(value) => toggleGroupAllVisibility(groupValue, value)"
									active-color="#95D475"
									inactive-color="#dcdfe6"
								/>
							</div>
						</div>
					</div>

					<!-- 单颗卫星列表 -->
					<div class="individual_satellites">
						<div
							v-for="satellite in getIndividualSatellites(groupValue)"
							:key="satellite.id"
							class="individual_satellite_item"
						>
							<div class="satellite_info">
								<span class="individual_satellite_name">{{ satellite.name }}</span>
							</div>
							<div class="satellite_controls">
								<el-button
									size="small"
									type="info"
									plain
									@click="showSatelliteTleData(satellite, groupValue)"
									class="tle_button"
								>
									TLE
								</el-button>
								<el-switch
									:model-value="individualSatelliteVisibility.get(satellite.id)"
									@change="(val) => toggleIndividualSatellite(satellite.id, val)"
									size="small"
								/>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="empty_state" v-else>
				<p>暂无已选择的卫星</p>
				<p>请在左侧面板选择卫星星座</p>
			</div>
		</div>
	</el-drawer>
</template>

<script setup>
import * as Cesium from 'cesium';
import 'cesium/Build/Cesium/Widgets/widgets.css';
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { View, Hide, Refresh, Close } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import './SatelliteTrack.scss';
import { getTleData, getCacheStats, clearAllCache, updateTleData } from '@/http/index';
// import cacheManager from '@/utils/cacheManager.js'; // 暂未使用
import SatelliteEntity from '@/js/SatelliteEntity';
import OrbitDesigner from '@/components/orbit-designer/OrbitDesigner.vue';
import {
	specialSatellite,
	weatherSatellite,
	communicationSatellite,
	navigationSatellite,
	scientificSatellite,
	miscellaneousSatellite
} from './satelliteType';
import { compareArrays } from '@/utils';
import gaodeImage from '@/assets/gaode.jpg';
import CachedImageryProvider from '@/utils/CachedImageryProvider.js';

const allSatellite = [
	...specialSatellite,
	...weatherSatellite,
	...communicationSatellite,
	...navigationSatellite,
	...scientificSatellite,
	...miscellaneousSatellite
];

// 为表格提供过滤后的数据（去除标题项）
const specialSatelliteData = computed(() => specialSatellite.filter((item) => !item.type));
const weatherSatelliteData = computed(() => weatherSatellite.filter((item) => !item.type));
const communicationSatelliteData = computed(() => communicationSatellite.filter((item) => !item.type));
const navigationSatelliteData = computed(() => navigationSatellite.filter((item) => !item.type));
const scientificSatelliteData = computed(() => scientificSatellite.filter((item) => !item.type));
const miscellaneousSatelliteData = computed(() => miscellaneousSatellite.filter((item) => !item.type));

window.CESIUM_BASE_URL = import.meta.env.MODE === 'development' ? '/cesium' : '/satellite-track/cesium';

let viewer;
// 保存分组的卫星实例
const satelliteMap = new Map();
// 轨道预测设置
const orbitPredictionHours = ref(24); // 默认24小时
const totalSeconds = computed(() => orbitPredictionHours.value * 3600); // 动态计算总秒数
// 响应式数据
const drawer = ref(false);
const selectedDrawer = ref(false); // 已选卫星抽屉
const cacheDrawer = ref(false);
const orbitDesignerVisible = ref(false); // 轨道设计器面板显示状态
// 默认勾选
const checked = ref([]);
// 已选择的卫星信息
const selectedSatellites = ref(new Map());
// 卫星显示状态
const satelliteVisibility = ref(new Map());
// 存储每颗卫星的详细信息和状态
const individualSatellites = ref(new Map()); // key: satelliteGroup, value: Array of satellite objects
const individualSatelliteVisibility = ref(new Map()); // key: satelliteId, value: boolean
// 地球自转控制
const earthRotationEnabled = ref(false); // 地球自转状态
// 场景模式检测
const is3DMode = ref(true); // 默认为3D模式
// 存储每个卫星组的全部显示状态
const groupAllVisibility = ref(new Map()); // key: satelliteGroup, value: boolean

// 缓存相关状态
const isUpdatingTle = ref(false);
const updateProgress = ref({ current: 0, total: 0, currentGroup: '' });
const cacheStats = ref({
	tleGroups: 0,
	totalSize: 0,
	oldestTimestamp: null,
	newestTimestamp: null
});

// 地图瓦片缓存相关
let cachedImageryProvider = null;
const mapCacheStats = ref({
	tileCount: 0,
	totalSize: 0,
	oldestTimestamp: null,
	newestTimestamp: null
});
const isMapCacheEnabled = ref(true);

// 存储每个星座的卫星数量
const constellationCounts = ref(new Map());

Cesium.Ion.defaultAccessToken =
	'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiYjZmMWM4Ny01YzQ4LTQ3MzUtYTI5Mi1hNTgyNjdhMmFiMmMiLCJpZCI6NjIwMjgsImlhdCI6MTYyNjY3MTMxNX0.5SelYUyzXWRoMyjjFvmFIAoPtWlJPQMjsVl2e_jQe-c';

function initCesium() {
	// 复写原型方法 用于timeline组件日期格式化；
	Cesium.Timeline.prototype.makeLabel = function (time) {
		let minutes = 0 - new Date().getTimezoneOffset();
		let dataZone8 = Cesium.JulianDate.addMinutes(time, minutes, new Cesium.JulianDate());
		return Cesium.JulianDate.toIso8601(dataZone8).slice(0, 19);
	};

	//高德卫星地图（带缓存功能）
	cachedImageryProvider = new CachedImageryProvider({
		url: 'https://webst{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
		minimumLevel: 3,
		maximumLevel: 18,
		tilingScheme: new Cesium.WebMercatorTilingScheme(),
		enableCache: isMapCacheEnabled.value,
		subdomains: ['01', '02', '03', '04']
	});

	let gaoDeSatelliteImgLayer = cachedImageryProvider;

	viewer = new Cesium.Viewer('cesiumContainer', {
		baseLayerPicker: true,
		geocoder: false,
		navigationHelpButton: false,
		infoBox: false
	});

	const customLayerViewModel = new Cesium.ProviderViewModel({
		name: '高德地图',
		iconUrl: gaodeImage,
		tooltip: '高德地图',
		category: 'Cesium ion', // 或 'Other 、Cesium ion'、'Bing Maps' 等
		creationFunction: function () {
			return gaoDeSatelliteImgLayer;
		}
	});

	viewer.baseLayerPicker.viewModel.imageryProviderViewModels.unshift(customLayerViewModel);

	// 设置高德地图为默认图层
	const selectedViewModel = viewer.baseLayerPicker.viewModel.imageryProviderViewModels[0];
	viewer.baseLayerPicker.viewModel.selectedImagery = selectedViewModel;

	// 时间格式化
	let minutes = 0 - new Date().getTimezoneOffset(); // 0 - (-480);
	viewer.animation.viewModel.timeFormatter = function (date) {
		let dataZone8 = Cesium.JulianDate.addMinutes(date, minutes, new Cesium.JulianDate());
		return Cesium.JulianDate.toIso8601(dataZone8).slice(11, 19);
	};
	viewer.animation.viewModel.dateFormatter = function (date) {
		let dataZone8 = Cesium.JulianDate.addMinutes(date, minutes, new Cesium.JulianDate());
		return Cesium.JulianDate.toIso8601(dataZone8).slice(0, 10);
	};

	Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
		75.0, // 西经
		10.0, // 南纬
		140.0, // 东经
		60.0 // 北纬
	);

	// 监听场景模式变化
	viewer.scene.morphComplete.addEventListener(() => {
		is3DMode.value = viewer.scene.mode === Cesium.SceneMode.SCENE3D;
		// 如果地球自转正在运行，需要重新应用设置以适应新的模式
		if (earthRotationEnabled.value) {
			// 先停止当前的自转设置
			stopEarthRotation();
			// 重新启动以适应新模式
			startEarthRotation();
		}
	});

	// 初始化场景模式状态
	is3DMode.value = viewer.scene.mode === Cesium.SceneMode.SCENE3D;
}

function initTimeLine() {
	const start = Cesium.JulianDate.fromIso8601(new Date().toISOString());
	const stop = Cesium.JulianDate.addSeconds(start, totalSeconds.value, new Cesium.JulianDate());
	viewer.clock.startTime = start.clone();
	viewer.clock.stopTime = stop.clone();
	viewer.clock.currentTime = start.clone();
	viewer.timeline.zoomTo(start, stop);
	viewer.clock.multiplier = 1;
	viewer.clock.shouldAnimate = true;
	viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
}

function parseTle(data = '') {
	if (data.length === 0) return;
	let result = data.split('\r\n');
	let tles = [],
		i = 0,
		tem = [];
	result.forEach((item) => {
		i++;
		tem.push(item);
		if (i === 3) {
			tles.push(tem.join('\r\n'));
			tem = [];
			i = 0;
		}
	});
	return tles;
}

function addCesiumEventListener() {
	let callback = viewer.screenSpaceEventHandler.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
	viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
		callback(movement);
		const pickedFeature = viewer.scene.pick(movement.position);

		if (!Cesium.defined(pickedFeature)) {
			// 点击空白区域，可以在这里添加取消选择的逻辑
			console.log('点击了空白区域');
			return;
		}

		if (pickedFeature && pickedFeature.id) {
			// 点击了卫星实体
			const entity = pickedFeature.id;
			console.log('点击了卫星:', entity.name || entity.id);

			// 显示卫星信息或执行其他交互逻辑
			if (entity.name) {
				ElMessage.info(`选中卫星: ${entity.name}`);
			}

			// 可以在这里添加更多的卫星点击交互逻辑
			// 比如显示卫星详细信息、轨道信息等
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

// 卫星选择变化事件处理
function handleSatelliteChange(checkedValues) {
	// 这个函数会在用户勾选/取消勾选卫星组时被调用
	console.log('卫星选择发生变化:', checkedValues);

	// 更新已选卫星的统计信息
	updateSelectedSatellitesCount();
}

// 更新已选卫星数量统计
function updateSelectedSatellitesCount() {
	// let totalCount = 0; // 暂未使用
	// satelliteMap.forEach((satelliteSet) => {
	// 	totalCount += satelliteSet.size;
	// });

	// 更新选中卫星的Map
	selectedSatellites.value.clear();
	checked.value.forEach((satelliteGroup) => {
		const groupInfo = allSatellite.find((item) => item.value === satelliteGroup);
		if (groupInfo && satelliteMap.has(satelliteGroup)) {
			selectedSatellites.value.set(satelliteGroup, {
				name: groupInfo.label,
				count: satelliteMap.get(satelliteGroup).size,
				visible: satelliteVisibility.value.get(satelliteGroup) !== false
			});
		}
	});
}

// 控制单个卫星组的显示/隐藏
// function toggleSatelliteVisibility(satelliteGroup, visible) { // 暂未使用
// 	if (satelliteMap.has(satelliteGroup)) {
// 		const satelliteList = satelliteMap.get(satelliteGroup);
// 		satelliteList.forEach((entity) => {
// 			entity.show = visible;
// 		});
// 		satelliteVisibility.value.set(satelliteGroup, visible);
// 	}
// }

// 获取卫星数量
function getSatelliteCount(groupValue) {
	if (satelliteMap.has(groupValue)) {
		return satelliteMap.get(groupValue).size;
	}
	return 0;
}

// 获取星座的卫星数量（用于表格显示）
async function getConstellationSatelliteCount(groupValue) {
	if (!groupValue) return 0;

	try {
		// 如果已经加载过，直接返回数量
		if (satelliteMap.has(groupValue)) {
			return satelliteMap.get(groupValue).size;
		}

		// 如果没有加载过，从缓存或网络获取TLE数据来计算数量
		const tleData = await getTleDataLocal(groupValue);
		if (tleData) {
			const parsedResult = parseTle(tleData);
			return parsedResult ? parsedResult.length : 0;
		}
		return 0;
	} catch (error) {
		console.error(`获取星座 ${groupValue} 卫星数量失败:`, error);
		return 0;
	}
}

// 控制单颗卫星的显示/隐藏
function toggleIndividualSatellite(satelliteId, visible) {
	individualSatelliteVisibility.value.set(satelliteId, visible);

	// 找到对应的卫星实体
	for (const [, satellites] of individualSatellites.value) {
		const satellite = satellites.find((sat) => sat.id === satelliteId);
		if (satellite) {
			satellite.entity.show = visible;
			satellite.visible = visible;
			break;
		}
	}
}

// 获取卫星组中的所有卫星
function getIndividualSatellites(groupValue) {
	return individualSatellites.value.get(groupValue) || [];
}

// 批量控制卫星组中所有卫星的显示状态
function toggleAllIndividualSatellites(groupValue, visible) {
	const satellites = individualSatellites.value.get(groupValue);
	if (satellites) {
		satellites.forEach((satellite) => {
			toggleIndividualSatellite(satellite.id, visible);
		});
		// 更新组的全部显示状态
		groupAllVisibility.value.set(groupValue, visible);
	}
}

// 切换卫星组的全部显示状态
function toggleGroupAllVisibility(groupValue, newState) {
	if (newState !== undefined) {
		// 从开关组件传入的值
		toggleAllIndividualSatellites(groupValue, newState);
	} else {
		// 手动调用时切换状态
		const currentState = groupAllVisibility.value.get(groupValue) || false;
		toggleAllIndividualSatellites(groupValue, !currentState);
	}
}

// 更新选择的卫星状态
// function updateSelectedSatellites(satelliteGroup, isSelected) { // 暂未使用
// 	if (isSelected) {
// 		const groupInfo = getSatelliteGroupInfo(satelliteGroup);
// 		if (groupInfo) {
// 			selectedSatellites.value.set(satelliteGroup, groupInfo);
// 			satelliteVisibility.value.set(satelliteGroup, true);
// 			// 初始化组的全部显示状态为false（默认隐藏）
// 			groupAllVisibility.value.set(satelliteGroup, false);
// 		}
// 	} else {
// 		selectedSatellites.value.delete(satelliteGroup);
// 		satelliteVisibility.value.delete(satelliteGroup);
// 		groupAllVisibility.value.delete(satelliteGroup);
// 	}
// }

// 获取tle数据，优先从本地缓存获取
async function getTleDataLocal(path) {
	try {
		return await getTleData(path);
	} catch (error) {
		ElMessage.error(`获取TLE数据失败: ${error.message}`);
		throw error;
	}
}

// 创建satellite entity 实例
async function addSatellite(path) {
	// 判断map中是否已经包含对应的路径实例
	if (satelliteMap.has(path)) {
		let satelliteList = satelliteMap.get(path);
		satelliteList.forEach((item) => viewer.entities.add(item));
		// 设置默认可见性
		satelliteVisibility.value.set(path, true);
	} else {
		try {
			let result = await getTleDataLocal(path);
			let parsedResult = parseTle(result);
			let satelliteSet = new Set();
			let satelliteInfoArray = [];

			parsedResult.forEach((tle) => {
				let satellite = new SatelliteEntity(tle, {
					totalSeconds: totalSeconds.value
				});
				let cesiumSateEntity = satellite.createSatelliteEntity();
				let entityResult = viewer.entities.add(cesiumSateEntity);
				satelliteSet.add(entityResult);

				// 存储单颗卫星信息
				const satelliteInfo = {
					id: entityResult.id,
					name: satellite.name,
					entity: entityResult,
					visible: true
				};
				satelliteInfoArray.push(satelliteInfo);
				// 设置单颗卫星的可见性状态
				individualSatelliteVisibility.value.set(entityResult.id, true);
			});

			satelliteMap.set(path, satelliteSet);
			// 存储卫星组的详细信息
			individualSatellites.value.set(path, satelliteInfoArray);
			// 设置默认可见性
			satelliteVisibility.value.set(path, true);
		} catch (error) {
			console.error(`添加卫星失败: ${path}`, error);
			// 如果添加失败，从选择列表中移除
			const index = checked.value.indexOf(path);
			if (index > -1) {
				checked.value.splice(index, 1);
			}
		}
	}
}

function removeSatellite(path) {
	if (satelliteMap.has(path)) {
		let satelliteList = satelliteMap.get(path);
		satelliteList.forEach((item) => viewer.entities.remove(item));

		// 清理单颗卫星的数据
		if (individualSatellites.value.has(path)) {
			const satellites = individualSatellites.value.get(path);
			satellites.forEach((sat) => {
				individualSatelliteVisibility.value.delete(sat.id);
			});
			individualSatellites.value.delete(path);
		}
	}
}

watch(checked, (newValue, oldValue) => {
	const { addedItems, removedItems } = compareArrays(oldValue, newValue);
	if (addedItems.length) {
		// 默认只会有一次操作，也就是说addedItems, removedItems数组中的元素只会有一个，可以直接取第一个元素
		const satelliteGroup = addedItems[0];
		addSatellite(satelliteGroup).then(() => {
			// 卫星加载完成后更新统计信息
			updateSelectedSatellitesCount();
		});
	}
	if (removedItems.length) {
		const satelliteGroup = removedItems[0];
		removeSatellite(satelliteGroup);
		// 更新统计信息
		updateSelectedSatellitesCount();
	}
});

// TLE数据更新相关功能

// 更新所有TLE数据
// 手动更新TLE数据
async function handleManualTleUpdate() {
	try {
		// 获取所有可用的卫星组（不仅仅是已缓存的）
		const availableGroups = allSatellite.filter((item) => item.value && !item.type);

		if (availableGroups.length === 0) {
			ElMessage.info('没有可用的卫星组');
			return;
		}

		// 创建选项列表
		const options = availableGroups.map((group) => {
			return {
				label: group.label,
				value: group.value
			};
		});

		// 使用Element Plus的选择器
		const { value: selectedGroups } = await ElMessageBox.prompt(
			'请选择要下载/更新的卫星组（多选请用逗号分隔）：\n' +
				options.map((opt, index) => `${index + 1}. ${opt.label}`).join('\n'),
			'手动更新TLE数据',
			{
				confirmButtonText: '开始更新',
				cancelButtonText: '取消',
				inputPlaceholder: '输入序号，如：1,3,5 或输入 all 更新全部',
				inputValidator: (value) => {
					if (!value || value.trim() === '') {
						return '请输入要更新的卫星组序号';
					}
					if (value.toLowerCase() === 'all') {
						return true;
					}
					const numbers = value.split(',').map((n) => parseInt(n.trim()));
					const isValid = numbers.every((n) => !isNaN(n) && n >= 1 && n <= options.length);
					return isValid || '请输入有效的序号范围（1-' + options.length + '）';
				}
			}
		);

		let groupsToUpdate = [];
		if (selectedGroups.toLowerCase() === 'all') {
			groupsToUpdate = availableGroups.map((group) => group.value);
		} else {
			const indices = selectedGroups.split(',').map((n) => parseInt(n.trim()) - 1);
			groupsToUpdate = indices.map((i) => options[i].value);
		}

		// 开始更新
		isUpdatingTle.value = true;
		updateProgress.value = {
			current: 0,
			total: groupsToUpdate.length,
			currentGroup: ''
		};

		let successCount = 0;
		let failedCount = 0;

		for (let i = 0; i < groupsToUpdate.length; i++) {
			const group = groupsToUpdate[i];
			const groupInfo = allSatellite.find((item) => item.value === group);
			updateProgress.value.current = i + 1;
			updateProgress.value.currentGroup = groupInfo ? groupInfo.label : group;

			try {
				await updateTleData(group);
				successCount++;
				console.log(`手动更新成功: ${group}`);
			} catch (error) {
				failedCount++;
				console.error(`手动更新失败: ${group}`, error);
			}
		}

		isUpdatingTle.value = false;

		if (successCount > 0) {
			ElMessage.success(`手动更新完成！成功: ${successCount}, 失败: ${failedCount}`);
		} else {
			ElMessage.warning('所有更新都失败了');
		}

		// 更新缓存统计
		await loadCacheStats();
	} catch (error) {
		isUpdatingTle.value = false;
		if (error !== 'cancel') {
			ElMessage.error(`手动更新失败: ${error.message}`);
		}
	}
}

// 清空所有缓存
async function handleClearCache() {
	try {
		const result = await ElMessageBox.confirm(
			'确定要清空所有TLE缓存数据吗？这将删除所有本地保存的卫星数据。',
			'确认清空',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		);

		if (result === 'confirm') {
			await clearAllCache();
			ElMessage.success('缓存已清空');
			await loadCacheStats();
		}
	} catch (error) {
		if (error !== 'cancel') {
			ElMessage.error(`清空缓存失败: ${error.message}`);
		}
	}
}

// 加载缓存统计信息
async function loadCacheStats() {
	try {
		const stats = await getCacheStats();
		cacheStats.value = stats;
	} catch (error) {
		console.error('获取缓存统计失败:', error);
	}
}

// 格式化文件大小
function formatFileSize(bytes) {
	if (bytes === 0) return '0 B';
	const k = 1024;
	const sizes = ['B', 'KB', 'MB', 'GB'];
	const i = Math.floor(Math.log(bytes) / Math.log(k));
	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 格式化时间
function formatTime(timestamp) {
	if (!timestamp) return '无';
	return new Date(timestamp).toLocaleString('zh-CN');
}

// 地图瓦片缓存管理函数
// 加载地图缓存统计信息
async function loadMapCacheStats() {
	try {
		if (cachedImageryProvider) {
			const stats = await cachedImageryProvider.getCacheStats();
			mapCacheStats.value = stats;
		}
	} catch (error) {
		console.error('获取地图缓存统计失败:', error);
	}
}

// 清空地图缓存
async function handleClearMapCache() {
	try {
		const result = await ElMessageBox.confirm(
			'确定要清空所有地图瓦片缓存吗？这将删除所有本地保存的地图数据。',
			'确认清空',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		);

		if (result === 'confirm') {
			if (cachedImageryProvider) {
				await cachedImageryProvider.clearCache();
				ElMessage.success('地图缓存已清空');
				await loadMapCacheStats();
			}
		}
	} catch (error) {
		if (error !== 'cancel') {
			ElMessage.error(`清空地图缓存失败: ${error.message}`);
		}
	}
}

// 切换地图缓存状态
function toggleMapCache() {
	isMapCacheEnabled.value = !isMapCacheEnabled.value;
	if (cachedImageryProvider) {
		cachedImageryProvider.setEnableCache(isMapCacheEnabled.value);
	}
	ElMessage.success(`地图缓存已${isMapCacheEnabled.value ? '启用' : '禁用'}`);
}

// 显示卫星TLE数据
async function showSatelliteTleData(satellite, groupValue) {
	try {
		// 获取该卫星组的TLE数据
		const tleData = await getTleData(groupValue);

		if (!tleData) {
			ElMessage.error('无法获取TLE数据');
			return;
		}

		// 解析TLE数据找到对应的卫星
		const tleLines = tleData.split('\r\n');
		let satelliteTle = '';

		// 查找匹配的卫星名称
		for (let i = 0; i < tleLines.length; i += 3) {
			if (i + 2 < tleLines.length) {
				const name = tleLines[i].trim();
				const line1 = tleLines[i + 1];
				const line2 = tleLines[i + 2];

				if (name === satellite.name) {
					satelliteTle = `${name}\n${line1}\n${line2}`;
					break;
				}
			}
		}

		if (!satelliteTle) {
			ElMessage.warning(`未找到卫星 ${satellite.name} 的TLE数据`);
			return;
		}

		// 使用MessageBox显示TLE数据
		await ElMessageBox.alert(satelliteTle, `卫星 ${satellite.name} 的TLE数据`, {
			confirmButtonText: '确定',
			customStyle: {
				width: '600px'
			},
			customClass: 'tle-data-dialog'
		});
	} catch (error) {
		console.error('显示TLE数据失败:', error);
		ElMessage.error(`显示TLE数据失败: ${error.message}`);
	}
}

// 加载所有星座的卫星数量
async function loadConstellationCounts() {
	const allGroups = allSatellite.filter((item) => item.value && !item.type);

	for (const group of allGroups) {
		try {
			const count = await getConstellationSatelliteCount(group.value);
			constellationCounts.value.set(group.value, count);
		} catch (error) {
			console.error(`加载星座 ${group.value} 数量失败:`, error);
			constellationCounts.value.set(group.value, 0);
		}
	}
}

// 获取星座卫星数量（用于模板显示）
function getConstellationCount(groupValue) {
	return constellationCounts.value.get(groupValue) || 0;
}

// 处理预测长度变化
function handlePredictionLengthChange(newHours) {
	// 保存到本地存储
	localStorage.setItem('orbitPredictionHours', newHours.toString());

	// 重新初始化时间线
	if (viewer) {
		initTimeLine();
	}

	// 如果有已选择的卫星，需要重新创建卫星实体以应用新的预测时长
	if (selectedSatellites.value.size > 0) {
		// 重新加载所有已选择的卫星
		for (const [groupValue] of selectedSatellites.value) {
			reloadSatelliteGroup(groupValue);
		}
	}

	ElMessage.success(`轨道预测时长已更新为 ${formatPredictionLength(newHours)}`);
}

// 格式化预测长度显示
function formatPredictionLength(hours) {
	if (hours < 24) {
		return `${hours}小时`;
	} else if (hours < 168) {
		return `${Math.round(hours / 24)}天`;
	} else {
		return `${Math.round(hours / 168)}周`;
	}
}

// 地球自转控制功能
function toggleEarthRotation(value) {
	// 如果传入了值（来自switch组件），使用传入的值；否则切换当前状态
	if (typeof value === 'boolean') {
		earthRotationEnabled.value = value;
	} else {
		earthRotationEnabled.value = !earthRotationEnabled.value;
	}

	if (earthRotationEnabled.value) {
		startEarthRotation();
		ElMessage.success('地球自转已开启');
	} else {
		stopEarthRotation();
		ElMessage.info('地球自转已关闭');
	}
}

// 开始地球自转 - 在3D模式下实现视觉自转，在2D模式下显示光照
function startEarthRotation() {
	if (!viewer) return;

	// 启用地球光照效果，在所有模式下显示昼夜变化
	viewer.scene.globe.enableLighting = true;

	// 只在3D模式下设置相机变换实现视觉自转
	if (viewer.scene.mode === Cesium.SceneMode.SCENE3D) {
		const icrfTransform = Cesium.Transforms.computeIcrfToFixedMatrix(viewer.clock.currentTime);
		if (Cesium.defined(icrfTransform)) {
			const camera = viewer.camera;
			const offset = Cesium.Cartesian3.clone(camera.position);
			const transform = Cesium.Matrix4.fromRotationTranslation(icrfTransform);
			camera.lookAtTransform(transform, offset);
		}

		// 添加预渲染事件监听器，持续更新ICRF变换
		viewer.scene.preRender.addEventListener(updateIcrfTransform);
	}
}

// 停止地球自转
function stopEarthRotation() {
	if (!viewer) return;

	// 关闭地球光照效果
	viewer.scene.globe.enableLighting = false;

	// 只在3D模式下清理相机变换相关设置
	if (viewer.scene.mode === Cesium.SceneMode.SCENE3D) {
		// 移除预渲染事件监听器
		viewer.scene.preRender.removeEventListener(updateIcrfTransform);

		// 恢复相机变换为默认状态
		viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
	}
}

// ICRF变换更新函数（仅在3D模式下进行相机变换）
function updateIcrfTransform() {
	if (!viewer) {
		return;
	}

	// 在所有模式下都更新光照，但只在3D模式下进行相机变换
	if (viewer.scene.mode === Cesium.SceneMode.SCENE3D) {
		const icrfTransform = Cesium.Transforms.computeIcrfToFixedMatrix(viewer.clock.currentTime);
		if (Cesium.defined(icrfTransform)) {
			const camera = viewer.camera;
			const offset = Cesium.Cartesian3.clone(camera.position);
			const transform = Cesium.Matrix4.fromRotationTranslation(icrfTransform);
			camera.lookAtTransform(transform, offset);
		}
	}
}

// 生命周期
onMounted(async () => {
	// 从本地存储加载轨道预测设置
	const savedHours = localStorage.getItem('orbitPredictionHours');
	if (savedHours) {
		orbitPredictionHours.value = parseInt(savedHours);
	}

	initCesium();
	initTimeLine();
	addCesiumEventListener();
	await loadCacheStats();
	await loadMapCacheStats();
	await loadConstellationCounts();
});

// 组件销毁时清理资源
onUnmounted(() => {
	// 清理地球自转设置
	if (viewer && earthRotationEnabled.value) {
		stopEarthRotation();
	}
});
</script>
